package com.scatteredServer.config;



import com.scatteredServer.common.RedisDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 通过使用依赖导入的lettuce连接方式，配置可分库redis
 */
@Configuration
public class RedisConfig {

    //有配置需要继续添加
    @Value("${spring.data.redis.host}")
    private String host;
    @Value("${spring.data.redis.password}")
    private String password;


    //有需要继续配置
    @Bean("default")
    public RedisTemplate<String, Object> redisTemplate() {
        return createRedisTemplate(RedisDatabase.DEFAULT);
    }
    @Bean("use_1")
    public RedisTemplate<String, Object> redisTemplateUseDatabase1() {
        return createRedisTemplate(RedisDatabase.DATABASE_1);
    }
    @Bean("use_2")
    public RedisTemplate<String, Object> redisTemplateUseDatabase2() {
        return createRedisTemplate(RedisDatabase.DATABASE_2);
    }

    //创建redis数据库操作对象
    public RedisTemplate<String, Object> createRedisTemplate(RedisDatabase redisDatabase) {

        //lettuce连接redis条件配置
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);config.setPassword(password);

        /*
          lettuce连接池配置
          ······
         */

        RedisTemplate<String, Object> template = getRedisTemplate(redisDatabase, config);//获取指定库的redis数据库操作对象
        template.afterPropertiesSet();
        return template;
    }

    //生成指定库的redis数据库操作对象，如果配置了连接池则加一个传参即可
    private static RedisTemplate<String, Object> getRedisTemplate(RedisDatabase redisDatabase, RedisStandaloneConfiguration config) {

        //通过使用LettuceConnectionFactory可以设置指定库
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
        factory.setDatabase(redisDatabase.getIndex());
        factory.afterPropertiesSet();

        //设置序列化
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        /*template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(stringRedisSerializer);*/
        //把对象转为json字符串的序列化工具
        //template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

}
